<template>
  <el-main class="bg table_wrap customized_products">
    <div class='div-form'>
      <el-form ref="elFormRef" :model="formInline" label-width="90px" :style="{ width: '100%' }" label-position="left">
        <el-row :gutter="20">
									<el-col :xs="24" :sm="24" :lg="8" class="el_form_search_wrap">
				<el-form-item label="商品名称">
								<el-input v-model="formInline.product_name"></el-input>
							</el-form-item>
			</el-col>
								<el-col :xs="24" :sm="24" :lg="8" class="el_form_search_wrap">
				<el-form-item label="分类名称">
								<el-select v-model="formInline.classification_name">
													<el-option v-for="o in list_classification_name" :key="o.classification_name" :label="o.classification_name"
									   :value="o.classification_name">
							</el-option>
											</el-select>
							</el-form-item>
			</el-col>
																	<el-col :xs="24" :sm="24" :lg="8" class="el_form_search_wrap">
				<el-form-item label="生产日期">
								<el-input v-model="formInline.production_date"></el-input>
							</el-form-item>
			</el-col>
																														<el-col :xs="24" :sm="24" :lg="8" class="el_form_search_wrap">
				<el-form-item label="审核状态">
					<el-select v-model="formInline.examine_state">
						<el-option value="">全部</el-option>
						<el-option value="未审核">未审核</el-option>
						<el-option value="已通过">已通过</el-option>
						<el-option value="未通过">未通过</el-option>
					</el-select>
				</el-form-item>
			</el-col>
        </el-row>
      </el-form>
    </div>
    <baseTable :tableColumns="columns" requestApi='/api/customized_products/get_list' :isShowSelect="true" :vm="vm"
               v-model:isRefresh="isRefresh" :otherParams="formInline"
               @handleSelectionChange="handleSelectionChange"
               @handleCurrentChangeNew="handleCurrentChangeNew"
               @handleTableDataList="handleTableDataList"
               :isExportTableDataList="true"
               :refeminderFun='true'
               :ifsParams='ifsParams'
    >
      <!-- 头部按钮 -->
      <template #baseHeadFunt>
        <el-button type="primary" @click="onSubmit">查询</el-button>
        <el-button @click="onReset(true)">重置</el-button>
        <ExportButton style="display: inline-block; margin:0 8px;" v-if="$check_option('/customized_products/table', 'export_db')"
          :tableColumShowList="columns"
          :tableDataList="tableData"></ExportButton>
        <el-button v-if="$check_option('/customized_products/table', 'print')"@click="print('dataTable')"class="search_btn_print">打印</el-button>
        <el-button
            v-if="$check_action('/customized_products/table','del') || $check_action('/customized_products/view','del')"
            class="search_btn_del" type="danger" @click="delInfo()">删除
        </el-button>
        <downloadExcel style="display: inline-block; margin-left: 8px;" v-if="$check_option('/customized_products/table', 'import_db')"
          class="export-excel-wrapper" :data="details_form" :fields="json_fields" name="数据导入表格.xls">
            <el-button type="success">下载导入文档</el-button>
        </downloadExcel>
        <span style="display: inline-block; margin-left:8px;">
            <el-upload
              v-if="$check_option('/customized_products/table', 'import_db')"
              action
              accept=".xlsx, .xls"
              :auto-upload="false"
              :show-file-list="false"
              :on-change="handle_import">
            <el-button type="primary">导入</el-button>
        </el-upload>
        </span>
      </template>
      <!-- 操作 -->
      <template #baseTableFunt="{ scope }">
        <el-button type="primary" v-if="user_group == '管理员' || $check_action('/customized_products/table','set')" size="small"
                    @click="router.push('./view?customized_products_id='+scope.row.customized_products_id)">详情
        </el-button>
          <!--跨表按钮-->
              <el-button size="small" @click="to_table(scope.row,'../i_want_to_customize_it/view')"
            v-if="$check_action('/i_want_to_customize_it/table', 'add') ||$check_action('/i_want_to_customize_it/view', 'add')">
          <span>定制</span>
        </el-button>
                  <el-button type="primary" size="small" v-if="$check_action('/customized_products/table','set')"
                   @click="router.push('../comment/table?size=10&page=1&source_table=customized_products&source_field=' + field + '&source_id=' + scope.row[field])">
          查看评论
        </el-button>
        </template>
      <template #baseTableFunt2="{ scope }">
        <el-button type="primary" v-if="user_group == '管理员' || $check_action('/customized_products/table','set')" size="small"
            @click="router.push('./view?customized_products_id='+scope.customized_products_id)">详情
        </el-button>
      <!--跨表按钮-->
              <el-button size="small" @click="to_table(scope,'../i_want_to_customize_it/view')"
                   v-if="$check_action('/i_want_to_customize_it/table', 'add') ||$check_action('/i_want_to_customize_it/view', 'add')">
          <span>定制</span>
        </el-button>
              <el-button type="primary" size="small" v-if="$check_action('/customized_products/table','set')"
               @click="router.push('../comment/table?size=10&page=1&source_table=customized_products&source_field=' + field + '&source_id=' + scope[field])">
      查看评论
    </el-button>
        </template>
      <template #tableContent="{ scope, column }">
                                    <span v-if="column.prop === 'product_cover'">
        <el-image
            :preview-teleported="true"
            style="width: 60px; height: 60px"
            :src="$fullUrl($banseUrl,scope.row.product_cover)"
            :preview-src-list="[$fullUrl($banseUrl,scope.row.product_cover)]"
            :initial-index="0"
            fit="cover">
      </el-image>
      </span>
                                  <span v-if="column.prop === 'production_date'">{{$toTime(scope.row.production_date, "YYYY-MM-DD")}}</span>
                  <span v-if="column.prop === 'merchant_users'">{{ scope.row['merchant_users']?getObj(list_user_merchant_users,scope.row['merchant_users']).nickname+"-"+getObj(list_user_merchant_users,scope.row['merchant_users']).username:"" }}</span>
                  <span v-if="column.prop === 'shelf_life'">{{formatDate(scope.row.shelf_life)}}</span>
                  <a v-if="column.prop === 'customized_declaration'" :href="$fullUrl($banseUrl, scope.row['customized_declaration'])" target="_blank" style="color: rgb(64, 158, 255)">点击下载</a>
                                                  <span v-if="column.prop === 'qrcode_img'">
          <el-image
              :preview-teleported="true"
              style="width: 60px; height: 60px"
              :src="$fullUrl($banseUrl, scope.row.qrcode_img)"
              :preview-src-list="[$fullUrl($banseUrl, scope.row.qrcode_img)]"
              :initial-index="0"
              fit="cover"
          >
          </el-image>
        </span>
        <span v-if="column.prop === 'timing_start_time'">{{formatDate(scope.row.timing_start_time)}}</span>
        <span v-if="column.prop === 'timing_end_time'">{{formatDate(scope.row.timing_end_time)}}</span>
        <span v-if="column.prop === 'create_time'">{{formatDate(scope.row.create_time)}}</span>
        <span v-if="column.prop === 'update_time'">{{formatDate(scope.row.update_time)}}</span>
      </template>

      <template #tableContent2="{ scope, column }">

                                                                                                                                                                                                                                                          <span v-if="column.prop === 'production_date'"> {{ column.label }}：{{$toTime(scope.production_date, "YYYY-MM-DD")}}</span>
                                                    <span v-if="column.prop === 'merchant_users'"> {{ column.label }}：{{ scope['merchant_users']?getObj(list_user_merchant_users,scope['merchant_users']).nickname+"-"+getObj(list_user_merchant_users,scope['merchant_users']).username:"" }}</span>
                                                    <span v-if="column.prop === 'shelf_life'"> {{ column.label }}：{{formatDate(scope.shelf_life)}}</span>
                                                    <span v-if="column.prop === 'customized_declaration'">  {{ column.label }}<a :href="$fullUrl($banseUrl, scope.customized_declaration)" target="_blank" style="color: rgb(64, 158, 255)"> 点击下载</a></span>
                                                                                                                                                                                    <span v-if="column.prop === 'qrcode_img'">
          {{ column.label }}：
          <el-image
              :preview-teleported="true"
              style="width: 60px; height: 60px"
              :src="$fullUrl($banseUrl, scope.qrcode_img)"
              :preview-src-list="[$fullUrl($banseUrl, scope.qrcode_img)]"
              :initial-index="0"
              fit="cover"
          >
          </el-image>
        </span>
        <span v-if="column.prop === 'timing_start_time'">{{ column.label }}：{{formatDate(scope.timing_start_time)}}</span>
        <span v-if="column.prop === 'timing_end_time'">{{ column.label }}：{{formatDate(scope.timing_end_time)}}</span>
        <span v-if="column.prop === 'create_time'"> {{ column.label }}：{{formatDate(scope.create_time)}}</span>
        <span v-if="column.prop === 'update_time'"> {{ column.label }}：{{formatDate(scope.update_time)}}</span>
      </template>
    </baseTable>
                                </el-main>
</template>
<script setup>
  import {useRouter} from "vue-router";
  import * as XLSX from "xlsx";

  let router = useRouter();
  import {
          $get_auth,
          func,
          paramsFun,
          $fullUrl,
          formatDate,
          $banseUrl,
          $check_action,
          $toTime,
  } from "@/utils/utils.js";
  import { $post, $get } from "@/api/Api.js";
  import {Picture} from "@element-plus/icons-vue";
  import {ElMessage} from "element-plus";
  import {ref, toRefs, computed, onMounted} from "vue"
  import storageHelper from '@/libs/StorageHelper'

  let user_group = storageHelper.getUserInfo().user_group;
  let table = ref("customized_products")
  let field = ref("customized_products_id")
  let url_get_list = ref("/api/customized_products/get_list")
  let url_del = ref("/api/customized_products/del")
  // 头部搜索// 搜索
  let formInline = ref({
            "product_name": "",
                "classification_name": "",
                      "production_date": "",
                          "orderby": `create_time desc`
  })
let ifsParams=ref([
                        {
  title: "定制库存",
  factor: "customized_inventory",
  start: 0,
  end: 2,
  type: "数内",
  idx: 0
},
                                        ])
            // 分类名称列表
  let list_classification_name = ref([""]);
  //获取分类名称
  let get_list_classification_name = async() =>{
    let json = await $get("/api/classification_information/get_list");
    if(json.result){
      list_classification_name.value = json.result.list;
    }
    else if(json.error){
      console.error(json.error);
    }
  }
                                    // 用户列表
  let list_user_merchant_users=ref([])
  //商城卖家用户列表
  let get_list_user_merchant_users= async() =>{
    let json = await $get("/api/user/get_list?user_group=商家用户");
    if(json.result){
      list_user_merchant_users.value = json.result.list;
    }
    else if(json.error){
      console.error(json.error);
    }
  }
                                let tableData=ref([])
  let handleTableDataList=(data)=>{
    tableData.value=data
  }
  //打印开始
  let print = (tableid) => {
    let win = window.open("");
    let tableToPrintA = document.getElementById(tableid);
    win.document.write(tableToPrintA.outerHTML);
    win.document.write("</div></body></html>");
    win.document.close();
    win.focus();
    win.print();
    win.close();
  };
  //导入
  let details_form = ref([
    {
              product_number:"文本类型",
          product_name:"文本类型",
          classification_name:"下寻类型",
          product_cover:"图片类型",
          album:"图集类型",
          customized_inventory:"数字类型",
          production_date:"日期类型",
          merchant_users:"UID类型",
          shelf_life:"日长类型",
          customized_declaration:"文件类型",
          customized_types:"下选类型",
          customization_requirements:"下多类型",
          customized_pricing:"下随类型",
          explanation_remarks:"多文本类型",
          product_details:"编辑类型",
        },
  ]);

  let json_fields = ref({
        商品编号:'product_number',
      商品名称:'product_name',
      分类名称:'classification_name',
      商品封面:'product_cover',
      商品相册:'album',
      定制库存:'customized_inventory',
      生产日期:'production_date',
      商家用户:'merchant_users',
      保质时间:'shelf_life',
      定制声明:'customized_declaration',
      定制类型:'customized_types',
      定制要求:'customization_requirements',
      定制价格:'customized_pricing',
      说明备注:'explanation_remarks',
      商品详情:'product_details',
    });

  let readFile=(file)=>{//文件读取
    return new Promise(resolve => {
      let reader = new FileReader();
      reader.readAsBinaryString(file);//以二进制的方式读取
      reader.onload = ev =>{
        resolve(ev.target.result);
      }
    })
  }

  let handle_import = async (ev) => {
    let file = ev.raw;
    console.log(file);
    if (!file) {
      ElMessage.error(("文件打开失败"))

    } else {
      let data = await readFile(file);
      let workbook = XLSX.read(data, { type: "binary" }); //解析二进制格式数据
      let worksheet = workbook.Sheets[workbook.SheetNames[0]]; //获取第一个Sheet
      let result = XLSX.utils.sheet_to_json(worksheet); //json数据格式
      result.forEach((item) => {
        // 将中文的键名替换成英文的
        for (let k in json_fields.value) {
          let newKey = json_fields.value[k];
          if (newKey) {
            item[newKey] = item[k];
            delete item[k];
          }
        }
      });
      for (let i = 0; i < result.length; i++) {
        let url = "/api/customized_products/add";
        await $post(url, result[i]).then((json) => {
          console.log("提交结果：", json);
          if (json.result) {
            ElMessage.success("操作成功");
            isRefresh.value = true;
          } else if (json.error) {
            ElMessage.error(json.error.message);
          }
        });
      }
    }
  };
  let to_table = (row, url) => {
    window.localStorage.setItem("form", JSON.stringify(row));
    router.push(url);
  };
  let vm = ref({
                                                    img: "product_cover",
                                                                                                                                                    id: "customized_products_id"
  })
  // 列名
  const columns =[
          {"prop": "product_number", "label": "商品编号",fieldType:1},
                {"prop": "product_name", "label": "商品名称",fieldType:1},
                {"prop": "classification_name", "label": "分类名称",fieldType:1},
                {"prop": "product_cover", "label": "商品封面",fieldType:4},
                {"prop": "album", "label": "商品相册",fieldType:1},
                {"prop": "customized_inventory", "label": "定制库存",fieldType:1},
                {"prop": "production_date", "label": "生产日期",fieldType:3},
                {"prop": "merchant_users", "label": "商家用户",fieldType:2},
                {"prop": "shelf_life", "label": "保质时间",fieldType:3},
                {"prop": "customized_declaration", "label": "定制声明",fieldType:4},
                {"prop": "customized_types", "label": "定制类型",fieldType:1},
                {"prop": "customization_requirements", "label": "定制要求",fieldType:1},
                {"prop": "customized_pricing", "label": "定制价格",fieldType:1},
                {"prop": "explanation_remarks", "label": "说明备注",fieldType:1},
              {"prop": "examine_state", "label": "审核状态",fieldType:1},
    { prop: "qrcode_title", label: "二维码标题" ,fieldType:1},
    { prop: "qrcode_img", label: "二维码照片",fieldType:4},
    { prop: "timer_title", label: "计时器标题" ,fieldType:1},
    {"prop": "timing_start_time", "label": "计时开始时间",fieldType:3},
    {"prop": "timing_end_time", "label": "计时结束时间",fieldType:3},
    { prop: "location_address", label: "当前位置" ,fieldType:1},
    { prop: "limit_times", label: "限制次数" ,fieldType:1},
    {"prop": "create_time", "label": "创建时间",fieldType:3},
    {"prop": "update_time", "label": "更新时间",fieldType:3},
  ]
  // 刷新table
  let isRefresh = ref(false)
  //批量勾选数据框
  let selectList = ref([])
  //点击数据
  let currentRowTableProduct = ref({})
  let showModal = ref(false)
                                // 关闭弹框
  let closeModal = () => {
    showModal.value = false;
  };
  //表格勾选回调
  let handleSelectionChange = (val) => {
    console.log(val)
    selectList.value = val.map((item) => {
      if (item.customized_products_id !== undefined) {
        return item.customized_products_id
      } else {
        return item
      }
    })
  }
  //点击当前行
  let handleCurrentChangeNew = (val) => {
    currentRowTableProduct.value = val
  }

  // 搜索
  let onSubmit = () => {
    isRefresh.value = true
  }
  // 重置
  let onReset = (refresh) => {
    formInline.value = {
                      "product_name": "",
                              "classification_name": "",
                                          "production_date": "",
                                                  "create_time": "",
      "orderby": `create_time desc`
    }
    isRefresh.value = refresh
  }
  // 批量删除删除
  let delInfo = () => {
    ElMessageBox.confirm(
        '此操作将永久删除该文件, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
    )
        .then(() => {
          selectList.value.map((item) => {
            delFun(item)
          })
        })
        .catch(() => {
          ElMessage({
            type: 'info',
            message: '取消操作',
          })
        })
  }
// 调用删除方法
let delFun = (id) => {
  $get(url_del.value,{customized_products_id: id}).then((json) => {
    if (json.result) {
      isRefresh.value = true;
      ElMessage.success("删除成功");
    } else if (json.error) {
      ElMessage.error(json.error);
    }
    isRefresh.value = true;
  });
};
  let get_list_before = () => {
    if(user_group != "管理员"){
              let sqlwhere = "(";
                                                                                                                                                                              if(user_group=="商家用户"){
                sqlwhere+= "merchant_users = " + this.user.user_id + " or ";
              }
                                                                                                                                                                          if (sqlwhere.length>1){
            sqlwhere = sqlwhere.substr(0,sqlwhere.length-4);
            sqlwhere += ")";
            formInline.value["sqlwhere"] = sqlwhere;
          }
        }
  }
  // 查询数组对象某个是否包含某个值,返回对应对象
  let getObj = (arr, val) => {
    let obj = arr.find((item) => item.user_id == val);
    if (obj) {
        return obj;
    } else {
        return "-";
    }
  };
  onMounted(() => {
    get_list_before()
              // 初始化分类名称列表
    get_list_classification_name()
                                  get_list_user_merchant_users()
                                })
</script>
<style lang="less" scoped>
  .div-form {
    padding: 10px;
  }
</style>